// SMTradeListViewController.m
#import "SMTradeListViewController.h"
#import "../../Views/Cells/SMTradeCell.h"
#import "../../Models/SMTradeItem.h"
#import <MJRefresh/MJRefresh.h>
#import "../../Managers/SMDataStore.h"
#import "../../Managers/Network/SMAPIClient.h"

@interface SMTradeListViewController ()
@property(nonatomic, assign) SMTradeListType type;
@property(nonatomic, strong) NSMutableArray<SMTradeItem *> *data;
@property(nonatomic, assign) NSInteger page;
@property(nonatomic, assign) BOOL hasMore;
@end

@implementation SMTradeListViewController

- (instancetype)initWithType:(SMTradeListType)type {
    if (self=[super initWithStyle:UITableViewStylePlain]) {
        _type=type;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.backgroundColor = UIColor.systemGroupedBackgroundColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:SMTradeCell.class forCellReuseIdentifier:@"cell"];

    self.data=[NSMutableArray array];
    self.page=1; self.hasMore=YES;

    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        __strong typeof(weakSelf) self = weakSelf; if (!self) return;
        self.page=1; self.hasMore=YES;
        [self requestPage:self.page];
    }];
    self.tableView.mj_footer=[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        __strong typeof(weakSelf) self = weakSelf; if (!self) return;
        if (self.hasMore) { self.page++; [self requestPage:self.page]; }
        else { [self.tableView.mj_footer endRefreshingWithNoMoreData]; }
    }];

    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - Network (primary) with fallback

- (void)requestPage:(NSInteger)page {
    NSString *path = (self.type==SMTradeListTypeSupply) ? @"trade/supply" : @"trade/demand";
    NSDictionary *params=@{@"page":@(page), @"pageSize":@(10)};
    __weak typeof(self) weakSelf=self;

    [[SMAPIClient shared] GET:path parameters:params success:^(id json) {
        __strong typeof(weakSelf) self = weakSelf; if (!self) return;
        NSArray *arr=nil;
        if([json isKindOfClass:NSDictionary.class] && [json[@"data"] isKindOfClass:NSArray.class]) arr=json[@"data"];
        else if([json isKindOfClass:NSArray.class]) arr=(NSArray*)json;

        if(!arr){
            [self applyData:[self fallbackPage:page] page:page];
            return;
        }

        NSMutableArray *parsed=[NSMutableArray arrayWithCapacity:arr.count];
        for(NSDictionary *d in arr){
            if(![d isKindOfClass:NSDictionary.class]) continue;
            SMTradeItem *it=[SMTradeItem new];
            it.itemId   = [NSString stringWithFormat:@"%@", d[@"id"] ?: [[NSUUID UUID] UUIDString]];
            it.title    = d[@"title"] ?: @"标题";
            // 详情更丰富：兼容后端 detail 字段为空时拼装
            NSString *spec = d[@"spec"] ?: @"Q235/重废";
            NSString *ton  = [d[@"tonnage"] respondsToSelector:@selector(stringValue)] ? [d[@"tonnage"] stringValue] : (d[@"tonnage"] ?: @"30");
            NSString *purity = d[@"purity"] ?: @"含铁≥98%";
            NSString *remark = d[@"detail"] ?: @"";
            if (remark.length == 0) {
                remark = [NSString stringWithFormat:@"规格：%@，约%@吨，%@。可检斤，支持上门看货。", spec, ton, purity];
            }
            it.detail  = remark;

            // 价格/城市
            it.price   = [d[@"price"] isKindOfClass:NSString.class] ? d[@"price"] : [d[@"price"] stringValue];
            it.city    = d[@"city"] ?: @"";

            // 图片优先用后端，否则随机网络图（真实场景）
            NSString *img = d[@"image"];
            if (img.length == 0) {
                img = [self randomRealImageURLForIndex:parsed.count seed:page];
            }
            it.imageURL= img;

            // 时间戳秒/毫秒兼容
            NSNumber *ts=d[@"updated_at"];
            if(ts) it.updatedAt=[NSDate dateWithTimeIntervalSince1970:([ts doubleValue] > 1000000000000 ? [ts doubleValue]/1000.0 : [ts doubleValue])];

            [parsed addObject:it];
        }
        [self applyData:parsed page:page];

    } failure:^(NSError *error) {
        __strong typeof(weakSelf) self = weakSelf; if (!self) return;
        [self applyData:[self fallbackPage:page] page:page];
    }];
}

#pragma mark - Fallback (local/mock with real network images)

- (NSArray<SMTradeItem *> *)fallbackPage:(NSInteger)page {
    // 优先用本地数据源（如果你已在 SMDataStore 填了真实数据）
//    NSArray *src = (self.type==SMTradeListTypeSupply) ? [SMDataStore shared].supply : [SMDataStore shared].demand;
//    if(src.count>0) return src;

    // 否则构造更丰富的模拟数据（带真实网络图片）
    NSArray<NSString *> *cities = @[@"上海",@"苏州",@"天津",@"成都",@"佛山",@"唐山",@"青岛",@"宁波"];
    NSArray<NSString *> *specs  = @[@"Q235重废",@"普中废",@"钢筋切粒",@"HMS 1/2",@"机械冲片",@"钢板边角料"];
    NSArray<NSString *> *purity = @[@"含铁≥98%",@"纯净度≥95%",@"杂质≤3%",@"含锈≤2%"];
    NSMutableArray *arr=[NSMutableArray arrayWithCapacity:10];
    for(int i=0;i<10;i++){
        SMTradeItem *it=[SMTradeItem new];
        it.itemId=[NSString stringWithFormat:@"%ld-%d",(long)page,i];
        BOOL isSupply = (self.type==SMTradeListTypeSupply);
        NSString *spec = specs[arc4random_uniform((uint32_t)specs.count)];
        NSString *ton  = [NSString stringWithFormat:@"%d", 20 + arc4random_uniform(60)]; // 20~79 吨
        NSString *pur  = purity[arc4random_uniform((uint32_t)purity.count)];
        it.title=[NSString stringWithFormat:@"%@·%@ #%d", (isSupply?@"供应":@"求购"), spec, i+1];
        it.detail=[NSString stringWithFormat:@"规格：%@，约%@吨，%@。可检斤，支持上门看货；付款方式可议。", spec, ton, pur];
        it.price=[NSString stringWithFormat:@"%d", 1800 + arc4random_uniform(700)]; // 1800~2499
        it.city=cities[arc4random_uniform((uint32_t)cities.count)];
        it.imageURL=[self randomRealImageURLForIndex:i seed:page];
        it.updatedAt=[NSDate dateWithTimeIntervalSinceNow:-(arc4random_uniform(7*24*3600))];
        [arr addObject:it];
    }
    return arr;
}

- (NSString *)randomRealImageURLForIndex:(NSInteger)idx seed:(NSInteger)page {
    // 用多源随机，尽量真实：废金属/工厂/仓库场景
    // picsum：稳定、无需 key；增加 seed 保证每条不同
    NSString *picsum = [NSString stringWithFormat:@"https://picsum.photos/seed/trade_%ld_%ld/640/420",
                        (long)page, (long)idx];

    // 也可以切换到 unsplash 的随机主题（如需更换，把下行 return 改成主题地址）
    // NSString *unsplash = [NSString stringWithFormat:@"https://source.unsplash.com/featured/?scrap,metal,factory,%ld_%ld",(long)page,(long)idx];

    return picsum;
}

#pragma mark - Apply

- (void)applyData:(NSArray<SMTradeItem *> *)arr page:(NSInteger)page {
    dispatch_async(dispatch_get_main_queue(), ^{
        if(page==1)[self.data removeAllObjects];
        [self.data addObjectsFromArray:arr];
        self.hasMore = arr.count>=10;

        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        if(self.hasMore) [self.tableView.mj_footer endRefreshing];
        else [self.tableView.mj_footer endRefreshingWithNoMoreData];

        // 空态占位（可按需自定义）
        if (self.data.count==0) {
            UILabel *empty = [UILabel new];
            empty.text = @"暂无信息";
            empty.textColor = UIColor.secondaryLabelColor;
            empty.textAlignment = NSTextAlignmentCenter;
            empty.frame = self.tableView.bounds;
            self.tableView.backgroundView = empty;
        } else {
            self.tableView.backgroundView = nil;
        }
    });
}

#pragma mark - table

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.data.count; }
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 116; }
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SMTradeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [cell configure:self.data[indexPath.row]];
    return cell;
}

@end
